$(document).ready(function(){
    $('.emosAuto[data-url]').each(function(){
        var url = $(this).attr('data-url');
        $(this).emos('init', {url:url});        
    });
});


$(document).ready(function(){
    $('.emosSettingsAuto[data-url]').each(function(){
        var url = $(this).attr('data-url');
        $(this).emosSettings('init', {url:url});        
    });
});


//
// Fields
//
$(document).ready(function(){
    $(".emosFields .tabs").tabs();   

    $('.emosFields').on('editorLoaded', '.editor', function(){        
        $('.expandHandler a', this).click(function(){
            var es = $(this).parents('.expandableSet:first');            
            var body = $('.expandBody', es);

            if(body.css('display') == 'none') {
                body.slideDown();
            }
            else {
                body.slideUp();                
            } 
            return false;            
        });         
    });

  
    
    $('.emosFields').on('editorLoaded', '.editor', function(){        
        $('textarea.ckeditor', this).each(function(){
            CKEDITOR.replace(this, {
                toolbar: $(this).attr('data-toolbar'),
                customConfig: $(this).attr('data-customConfig')       
            });             
        });

        $('input.datepicker', this).each(function(){
            $(this).datepicker({
                dateFormat: $(this).attr('data-format')
            });
        });        
    });             
    
    $('.emosFields').on('editorLoaded', '.editor', function(){        
        $('.latLng', this).each(function(){
            var latField = $('input.lat', this);
            var lngField = $('input.lng', this);
            var zoom = parseInt($(this).attr('data-zoom'));
            var mapDiv = $('.map', this)[0];
            
            function setPositionFields(position) {
                var lat = position.lat();
                var lng = position.lng();
                
                if(isNaN(lat)) lat = '';
                if(isNaN(lng)) lng = '';
                
                latField.val(lat);
                lngField.val(lng);                                  
            }   
            
            function getPositionFromFields() {
                var lat = parseFloat(latField.val());
                var lng = parseFloat(lngField.val());                
                return new google.maps.LatLng(lat, lng);
            }            
                                    
            var coords = getPositionFromFields();

            var mapOptions = {
              center: coords,
              zoom: zoom,
              mapTypeId: google.maps.MapTypeId.ROADMAP,
              scrollwheel: false
            };
            var map = new google.maps.Map(mapDiv, mapOptions);
            var marker = new google.maps.Marker({
                position: coords,
                map: map,
                draggable : true                
            });         
            
            google.maps.event.addListener(marker, 'drag', function() {
                setPositionFields(marker.getPosition());
            });            
            google.maps.event.addListener(map, 'click', function(data) {
                setPositionFields(data.latLng);                 
            }); 
            $('input', this).change(function(){                
                var position = getPositionFromFields();
                setPositionFields(position);
                map.setCenter(position);
                marker.setPosition(position);
            });

            
        });       
    });        
});

//
// Settings
//
(function( $ ) {
    $.fn.emosSettings = function(action, options) {

        function init(block, options) {                        
            block
                .addClass('emosSettings')
                .addClass('emosFields')
                .html(
                    "<div class='messages'></div>"+
                    "<div class='editor'></div>"
                );                        
                    
            var editor = $('div.editor', block);
            var messages = $('div.messages', block);       
            
            function showError(html) {
                messages.append($('<div class="message error"></div>').html(html));
            }
            
            function ajax(params, complete) {
                messages.empty();

                params.requestType = 'emosSettings';

                try{
                    $.post(options.url, params, function(data) {
                        if(data.source !== 'emosSettings') {                            
                            throw 'Bad EMOS signature';
                        }

                        if(data.messagesHtml) {
                            messages.html(data.messagesHtml);
                        }

                        if(data.formHtml !== undefined) {
                            editor.html(data.formHtml);                        
                            editor.trigger('editorLoaded');
                        }

                        if(complete instanceof Function) {
                            complete(data);                 
                        }

                    }, 'json')
                    .fail(function(xhr){                                 
                        showError('AJAX error');                        
                        if(xhr.status == 403) {
                            alert("Session lost!");
                            window.location.href = '?';
                        }
                    });                  
                }
                catch(ex) {
                    showError(ex);                     
                }
            }           
            
            // Save form
            $(editor).on("submit", "form", function(){ 
                var form = $(this);
                form.attr('action', options.url);                

                var action = $("input[name='action']", form).val();                                                              
                if(action == 'update') {
                    $(this).ajaxSubmit({
                        dataType : 'json',
                        data : {requestType: 'emosSettings'},
                        success : function(reply) {                                        
                            if(reply.exception) {
                                messages.html(reply.messagesHtml);
                                return;
                            }
                            
                            $('.item .error', editor).remove();
                            
                            if(reply.invalidFields) {
                                messages.html(reply.messagesHtml);
                                $.each(reply.invalidFields, function(name, error){
                                    var errorHtml = $("<div class='error'>").text(error);
                                    $(".item[data-field='"+name+"'] .control", editor).prepend(errorHtml);                                    
                                });                                
                            }
                            else {                                                                    
                                editor.empty();
                                ajax({action:'getForm'}, function(data){
                                    messages.html(reply.messagesHtml);
                                });                                   
                            }
                        },
                        error: function(xhr) {
                            showError('AJAX error');                        
                            if(xhr.status == 403) {
                                alert("Session lost!");
                                window.location.href = '?';
                            }                  
                        }                        
                    });                
                }
                
                return false;
            });        
            
            $(editor).on('click', 'input.null', function(){                
                var control = $('.nullableControl', $(this).parents('.item:first'));                
                if($(this).is(':checked')) {
                    control.hide();
                }
                else {
                    control.show();
                }
            });      
            
            // Initialization
            ajax({action:'init'}, function(data){
                block.attr('data-name', data.name);                                  
            });            
        }

        if (action === "init") {
            var settings = $.extend({
            }, options);

            this.each(function() {
                init($(this), options);            
            });   
        } 

    };
}( jQuery ));


//
// Tree
//
(function( $ ) {
    $.fn.emos = function(action, options) {
        function confirmDialog(html, okCallback, cancelCallback) {
            var div = $('<div />')
                    .attr('title', 'Confirm')
                    .html(html)                    
                    .appendTo("body");
            div.dialog({
                modal: true,
                buttons: {
                    'Ok': function() {
                        $(this).dialog('close');
                        if(okCallback) {
                            okCallback();
                        }
                    },
                    'Cancel': function() {
                        $(this).dialog('close');
                        if(cancelCallback) {
                            cancelCallback();
                        }                        
                    }
                }                
            });
        } 
        
        function init(block, options) {                        
            block
                .addClass('emos')
                .addClass('emosFields')
                .html(
                    "<div class='toolbar'></div>"+                
                    "<div class='breadcrumbs'></div>"+
                    "<div class='messages'></div>"+
                    "<div class='side'>"+                
                        "<div class='list'></div>"+                
                    "</div>"+                    
                    "<div class='main'>"+                
                        "<div class='editor'></div>"+                      
                    "</div>"+                    
                    "<div class='clear'></div>"                
                );
                    
            $('div.side', block).resizable({
                handles: 'e', 
                containmentType: block,
                minWidth: 100,
                maxWidth: block.width() - 100
            });        
                    
            var list = $('div.list', block);
            var editor = $('div.editor', block);
            var toolbar = $('div.toolbar', block);       
            var breadcrumbs = $('div.breadcrumbs', block);       
            var messages = $('div.messages', block);       
            
            function showError(html) {
                messages.append($('<div class="message error"></div>').html(html));
            }
            
            function ajax(params, complete) {
                messages.empty();

                params.requestType = 'emosTree';

                try{
                    $.post(options.url, params, function(data) {
                        if(data.source !== 'emos') {                            
                            throw 'Bad EMOS signature';
                        }

                        if(data.messagesHtml) {
                            messages.html(data.messagesHtml);
                        }

                        if(data.listHtml !== undefined) {
                            list.html(data.listHtml);
                        }
                        if(data.formHtml !== undefined) {
                            editor.html(data.formHtml);                        
                            editor.trigger('editorLoaded');

                        }
                        if(data.toolbarHtml !== undefined) {
                            toolbar.html(data.toolbarHtml);
                        }    
                        if(data.breadcrumbsHtml !== undefined) {
                            breadcrumbs.html(data.breadcrumbsHtml);
                        }                      

                        if(complete instanceof Function) {
                            complete(data);                 
                        }

                    }, 'json')
                    .fail(function(xhr){                                 
                        showError('AJAX error');                        
                        if(xhr.status == 403) {
                            alert("Session lost!");
                            window.location.href = '?';
                        }
                    });                  
                }
                catch(ex) {
                    showError(ex);                     
                }
            }
                        
            function getEntityName(element) {
                return $(element).parents('table[data-entity]:first').attr('data-entity');
            }
            
            function getPkValue(element) {                
                var pk = $(element).attr('data-pk');
                if(pk === undefined) {
                    return $(element).parents('[data-pk]:first').attr('data-pk');
                }
                else {
                    return pk;
                }
            }            
            

            // Initialization
            ajax({action:'init'}, function(data){
                block.attr('data-name', data.name);                
                
                if(data.mainHeight > 0) {
                    $('.list', block).css('height', data.mainHeight);
                    $('.editor', block).css('height', data.mainHeight);
                }                
            });

            
            // Select node
            $(list).on("click", "tr[data-pk]", function(event) {
                var entityName = getEntityName(this);
                var pkValue = getPkValue(this);                
                ajax({action:'selectNode', entityName:entityName, pkValue:pkValue, sub:false});                
                return false;
            });

            // Select empty sub item
            $(list).on("click", ".empty", function(event) {
                var entityName = getEntityName(this);
                var pkValue = getPkValue(this);
                ajax({action:'selectNode', entityName:entityName, pkValue:pkValue, sub:true});                
                return false;
            });            
            
            // Open branch
            $(list).on("click", "tr[data-pk] .open", function(event) {                
                var entityName = getEntityName(this);
                var pkValue = getPkValue(this);                
                ajax({action:'openBranch', entityName:entityName, pkValue:pkValue});                                
                return false;
            });      
            
            // Move items
            $(toolbar).on('click', '.moveUp, .moveDown, .moveTop, .moveBottom', function(){
                var position;
                if($(this).hasClass('moveUp')) {
                    position = 'up';
                }
                else if($(this).hasClass('moveDown')) {
                    position = 'down';
                }
                else if($(this).hasClass('moveTop')) {
                    position = 'top';
                }
                else if($(this).hasClass('moveBottom')) {
                    position = 'bottom';
                }                
                
                ajax({action:'move', position:position});
            });            
            
            // Close branch
            $(list).on("click", "tr[data-pk] .close", function(event) {
                var entityName = getEntityName(this);
                var pkValue = getPkValue(this);
                ajax({action:'closeBranch', entityName:entityName, pkValue:pkValue});                                                                                
                return false;
            });              
            
            // Close all branches
            $(toolbar).on('click', '.closeAllBranches', function(){
                ajax({action:'closeAllBranches'});
            });            

            // Breadcrumbs
            $(breadcrumbs).on('click', '.link', function(){
                var entityName = $(this).attr('data-entity');
                var pkValue    = $(this).attr('data-pk');
                ajax({action:'selectNode', entityName:entityName, pkValue:pkValue, sub:false});                
                return false;
            });                
            
            // Save form
            $(editor).on("submit", "form", function(){
                var form = $(this);
                form.attr('action', options.url);                

                var action = $("input[name='action']", form).val();                                                              
                if(action == 'update') {
                    $(this).ajaxSubmit({
                        dataType : 'json',
                        data : {requestType: 'emosTree'},
                        success : function(reply) {                                        
                            if(reply.exception) {
                                messages.html(reply.messagesHtml);
                                return;
                            }
                            
                            $('.item .error', editor).remove();
                            
                            if(reply.invalidFields) {
                                messages.html(reply.messagesHtml);
                                $.each(reply.invalidFields, function(name, error){
                                    var errorHtml = $("<div class='error'>").text(error);
                                    $(".item[data-field='"+name+"'] .control", editor).prepend(errorHtml);                                    
                                });                                
                            }
                            else {                            
                                var entityName = $("input[name='entityName']", form).val(); 
                                var pkValue    = $("input[name='pkValue']",    form).val();                                                  
                                ajax({action:'selectNode', entityName:entityName, pkValue:pkValue, sub:false}, function(){
                                    messages.html(reply.messagesHtml);
                                });   
                            }
                        },
                        error: function(xhr) {
                            showError('AJAX error');                        
                            if(xhr.status == 403) {
                                alert("Session lost!");
                                window.location.href = '?';
                            }                  
                        }                        
                    });                
                }
                else if(action == 'insert') {
                    $(this).ajaxSubmit({
                        dataType : 'json',
                        data : {requestType: 'emosTree'},
                        success : function(reply) {            
                            if(reply.exception) {
                                messages.html(reply.messagesHtml);
                                return;
                            }                    
                    
                            $('.item .error', editor).remove();
                    
                            if(reply.invalidFields) {
                                messages.html(reply.messagesHtml);
                                $.each(reply.invalidFields, function(name, error){
                                    var errorHtml = $("<div class='error'>").text(error);
                                    $(".item[data-field='"+name+"'] .control", editor).prepend(errorHtml);                                    
                                });                                
                            }
                            else {                            
                                var newEntityName = $("input[name='newEntityName']", form).val(); 
                                var newPkValue    = reply.newPkValue;                                                  
                                ajax({action:'selectNode', entityName:newEntityName, pkValue:newPkValue, sub:false}, function(){
                                    messages.html(reply.messagesHtml);
                                });  
                            }                    
                        },
                        error: function(xhr) {
                            showError('AJAX error');                        
                            if(xhr.status == 403) {
                                alert("Session lost!");
                                window.location.href = '?';
                            }                  
                        }                                 
                    });                                    
                }
                
                return false;
            });        
            
            // Delete
            $(toolbar).on('click', '.delete', function(){                
                confirmDialog('Delete current item?', function(){
                    ajax({action:'delete'});
                });         
            });                
            
            // New
            $(toolbar).on('click', '.new', function(){
                ajax({
                    action:             'getNewItemForm', 
                    parentEntityName:   $(this).attr('data-parentEntityName'),
                    parentPkValue:      $(this).attr('data-parentPkValue'),
                    newEntityName:      $(this).attr('data-newEntityName')
                });                 
            });    

            // Update schema
            $(toolbar).on('click', '.updateSchema', function(){
                ajax({action: 'updateSchema'});                 
            });        

            // Add fake
            $(toolbar).on('click', '.addFake', function(){
                ajax({action: 'addFake'});                 
            });              
            
            
            $(editor).on('click', 'input.null', function(){                
                var control = $('.nullableControl', $(this).parents('.item:first'));                
                if($(this).is(':checked')) {
                    control.hide();
                }
                else {
                    control.show();
                }
            });             
        }

        if (action === "init") {
            var settings = $.extend({
            }, options);

            this.each(function() {
                init($(this), options);            
            });   
        } 

    };
}( jQuery ));







